<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>照片上传与声纹注册</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#64748B',
                        success: '#10B981',
                        danger: '#EF4444',
                        dark: '#1E293B',
                        light: '#F8FAFC'
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .backdrop-blur-sm {
                backdrop-filter: blur(4px);
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .d-none {
                display: none;
            }
            .animate-shake {
                animation: shake 0.5s ease-in-out;
            }
        }
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
            20%, 40%, 60%, 80% { transform: translateX(5px); }
        }
        @keyframes pulse { 
            0% { opacity: 1; } 
            50% { opacity: 0.4; } 
            100% { opacity: 1; } 
        }
        .container { max-width: 800px; margin-top: 30px; }
        .card { margin-bottom: 20px; }
        .result { margin-top: 20px; padding: 15px; border-radius: 5px; }
        .success { background-color: #d1e7dd; color: #0f5132; }
        .error { background-color: #f8d7da; color: #842029; }
        .warning { background-color: #fff3cd; color: #664d03; }
        .recorder-container { margin-top: 15px; }
        .recorder-controls { display: flex; gap: 10px; margin-bottom: 10px; }
        .audio-preview { margin-top: 10px; padding: 15px; background-color: #f8f9fa; border-radius: 5px; }
        .btn-record { background-color: #dc3545; color: white; }
        .btn-stop { background-color: #ffc107; color: black; }
        .btn-send { background-color: #198754; color: white; }
        .recording-indicator { 
            display: inline-block; 
            width: 10px; 
            height: 10px; 
            background-color: #dc3545; 
            border-radius: 50%; 
            margin-right: 5px; 
            animation: pulse 1.5s infinite; 
        }
        .volume-meter {
            width: 100%;
            height: 30px;
            background: #e9ecef;
            border-radius: 4px;
            margin: 10px 0;
            overflow: hidden;
        }
        .volume-level {
            height: 100%;
            background: #3B82F6;
            width: 0%;
            transition: width 0.1s;
        }
    </style>
</head>
<body class="font-inter bg-gray-50 min-h-screen flex flex-col">
    <header class="bg-white shadow-sm sticky top-0 z-50 transition-all duration-300" id="header">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-cloud-upload text-primary text-2xl"></i>
                <h1 class="text-xl font-bold text-dark">数据录入</h1>
            </div>
            <nav class="hidden md:flex space-x-6">
                <a href="admin_home.html" class="text-gray-600 hover:text-primary transition-colors duration-200">首页</a>
                <a href="#" class="text-gray-600 hover:text-primary transition-colors duration-200">关于</a>
                <a href="#" class="text-gray-600 hover:text-primary transition-colors duration-200">帮助</a>
            </nav>
            <button class="md:hidden text-gray-600 focus:outline-none" id="mobile-menu-button">
                <i class="fa fa-bars text-xl"></i>
            </button>
        </div>
        <!-- 移动端菜单 -->
        <div class="md:hidden hidden bg-white shadow-md absolute w-full" id="mobile-menu">
            <div class="container mx-auto px-4 py-2 flex flex-col space-y-3">
                <a href="#" class="text-gray-600 hover:text-primary py-2 border-b border-gray-100 transition-colors duration-200">首页</a>
                <a href="#" class="text-gray-600 hover:text-primary py-2 border-b border-gray-100 transition-colors duration-200">关于</a>
                <a href="#" class="text-gray-600 hover:text-primary py-2 transition-colors duration-200">帮助</a>
            </div>
        </div>
    </header>

    <main class="flex-grow container mx-auto px-4 py-8">
        <section class="max-w-3xl mx-auto bg-white rounded-xl shadow-md p-6 md:p-8 transition-all duration-300 hover:shadow-lg">
            <div class="text-center mb-8">
                <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-dark mb-3">上传你的信息</h2>
                <p class="text-gray-600 max-w-2xl mx-auto">点击下方按钮上传你的照片并输入姓名、密码，我们将为你生成一个包含个人信息的文件。</p>
            </div>

            <div class="flex flex-col items-center justify-center h-64 md:h-80 bg-gray-50 rounded-lg border-2 border-dashed border-gray-300 mb-8 transition-all duration-300 hover:border-primary group cursor-pointer" id="upload-area">
                <i class="fa fa-cloud-upload text-4xl md:text-5xl text-gray-400 group-hover:text-primary transition-colors duration-300 mb-4"></i>
                <h3 class="text-lg font-medium text-gray-600 group-hover:text-primary transition-colors duration-300">点击上传信息</h3>
            </div>

            <div class="text-center">
                <button id="upload-btn" class="px-6 py-3 bg-primary hover:bg-primary/90 text-white font-medium rounded-lg shadow-md hover:shadow-lg transition-all duration-300 transform hover:-translate-y-0.5 flex items-center justify-center mx-auto">
                    <i class="fa fa-upload mr-2"></i>
                    上传照片
                </button>
            </div>

            <!-- 上传结果区域 -->
            <div id="result-area" class="mt-8 hidden">
                <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                    <div class="flex items-start">
                        <div class="flex-shrink-0">
                            <i class="fa fa-check-circle text-green-500 text-xl"></i>
                        </div>
                        <div class="ml-3">
                            <h3 class="text-sm font-medium text-green-800">上传成功</h3>
                            <div class="mt-2 text-sm text-green-700">
                                <p>JSON 文件已生成，你可以点击下方按钮下载。</p>
                            </div>
                            <div class="mt-4">
                                <button id="download-btn" class="px-4 py-2 bg-green-600 hover:bg-green-700 text-white text-sm font-medium rounded-md shadow hover:shadow-md transition-all duration-200 flex items-center">
                                    <i class="fa fa-download mr-2"></i>
                                    下载 JSON 文件
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <!-- 弹窗 -->
    <div id="upload-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 hidden flex items-center justify-center p-4">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md transform transition-all duration-300 scale-95 opacity-0" id="modal-content">
            <div class="p-6">
                <div class="flex justify-between items-start mb-4">
                    <h3 class="text-lg font-semibold text-gray-900">上传照片</h3>
                    <button id="close-modal" class="text-gray-400 hover:text-gray-500 focus:outline-none transition-colors duration-200">
                        <i class="fa fa-times text-xl"></i>
                    </button>
                </div>
                <form id="upload-form" class="space-y-4">
                    <div>
                        <label for="name" class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                        <input type="text" id="name" name="name" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all duration-200" placeholder="请输入你的姓名" required>
                    </div>
                    <div>
                        <label for="password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                        <input type="password" id="password" name="password" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all duration-200" placeholder="请输入你的密码" required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">照片</label>
                        <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg hover:border-primary transition-colors duration-200 cursor-pointer" id="photo-upload-area">
                            <div class="space-y-1 text-center">
                                <i class="fa fa-cloud-upload text-gray-400 text-3xl"></i>
                                <div class="flex text-sm text-gray-600">
                                    <label for="photo" class="relative cursor-pointer bg-white rounded-md font-medium text-primary hover:text-primary/80 transition-colors duration-200">
                                        <span>上传照片</span>
                                        <input id="photo" name="photo" type="file" accept="image/*" class="sr-only" required>
                                    </label>
                                    <p class="pl-1">或拖放文件</p>
                                </div>
                                <p class="text-xs text-gray-500">
                                    PNG, JPG (最大: 5MB)
                                </p>
                            </div>
                        </div>
                        <div id="photo-preview" class="hidden mt-3">
                            <img id="preview-image" src="" alt="预览图" class="max-h-40 rounded-lg border border-gray-200">
                        </div>
                    </div>
                    
                    <!-- 声纹注册部分 -->
                    <div class="card">
                        <div class="card-header">
                            <h5 class="font-medium text-gray-700 mb-2">2. 注册声纹特征</h5>
                        </div>
                        <div class="card-body">
                            <!-- 录音控件 -->
                            <div class="recorder-container">
                                <div class="recorder-controls">
                                    <button id="reg_startBtn" class="px-4 py-2 btn-record rounded-lg flex items-center">
                                        <i class="fa fa-microphone mr-2"></i> 开始录音
                                    </button>
                                    <button id="reg_stopBtn" class="px-4 py-2 btn-stop rounded-lg flex items-center" disabled>
                                        <i class="fa fa-stop mr-2"></i> 停止录音
                                    </button>
                                    <button id="reg_sendBtn" class="px-4 py-2 btn-send rounded-lg flex items-center" disabled>
                                        <i class="fa fa-paper-plane mr-2"></i> 发送录音
                                    </button>
                                </div>
                                <div id="reg_recordingStatus" class="text-sm text-gray-600 mb-2 d-none">
                                    <span class="recording-indicator"></span>
                                    <span id="reg_timer">剩余时间: 10秒</span>
                                </div>
                                <!-- 音量指示器 -->
                                <div class="volume-meter">
                                    <div id="reg_volumeMeter" class="volume-level"></div>
                                </div>
                                <div id="reg_audioPreview" class="audio-preview d-none">
                                    <h6 class="mb-2 font-medium text-gray-700">录音预览（可播放）</h6>
                                    <audio id="reg_audioPlayer" controls class="w-full mb-2"></audio>
                                    <div class="flex justify-between text-sm text-gray-500">
                                        <span>格式: WAV</span>
                                        <span>采样率: 16kHz | 位长: 16bit | 单声道</span>
                                    </div>
                                </div>
                            </div>
                            
                            <div id="reg_result" class="result d-none"></div>
                        </div>
                    </div>
                    
                    <div class="flex justify-end space-x-3 mt-6">
                        <button type="button" id="cancel-upload" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors duration-200">
                            取消
                        </button>
                        <button type="submit" class="px-4 py-2 bg-primary hover:bg-primary/90 text-white rounded-lg shadow hover:shadow-md transition-all duration-200">
                            确定
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // DOM 元素
        const uploadBtn = document.getElementById('upload-btn');
        const uploadModal = document.getElementById('upload-modal');
        const modalContent = document.getElementById('modal-content');
        const closeModal = document.getElementById('close-modal');
        const cancelUpload = document.getElementById('cancel-upload');
        const uploadForm = document.getElementById('upload-form');
        const nameInput = document.getElementById('name');
        const passwordInput = document.getElementById('password');
        const photoInput = document.getElementById('photo');
        const photoUploadArea = document.getElementById('photo-upload-area');
        const photoPreview = document.getElementById('photo-preview');
        const previewImage = document.getElementById('preview-image');
        const resultArea = document.getElementById('result-area');
        const downloadBtn = document.getElementById('download-btn');
        const mobileMenuButton = document.getElementById('mobile-menu-button');
        const mobileMenu = document.getElementById('mobile-menu');
        const uploadArea = document.getElementById('upload-area');
        const header = document.getElementById('header');

        // 录音管理器
        class AudioRecorder {
            constructor(type) {
                this.type = type;
                this.audioContext = null;
                this.mediaRecorder = null;
                this.audioChunks = [];
                this.recordingTimeout = null;
                this.analyser = null;
                this.maxRecordingTime = 10000; // 10秒限制
                this.volumeInterval = null;
                this.stream = null;
            }

            async start() {
                    try {
                        // 检查浏览器支持
                        if (!navigator.mediaDevices || !window.MediaRecorder) {
                            throw new Error('您的浏览器不支持录音功能');
                        }
            
                        // 初始化音频上下文
                        this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
                        
                        // 获取麦克风权限
                        this.stream = await navigator.mediaDevices.getUserMedia({ 
                            audio: {
                                echoCancellation: true,
                                noiseSuppression: true,
                                sampleRate: 16000,
                                channelCount: 1
                            },
                            video: false
                        });
                    
                    // 创建音频源
                    const source = this.audioContext.createMediaStreamSource(this.stream);
                    // 设置音量分析器
                     this.analyser = this.audioContext.createAnalyser();
					this.analyser.fftSize = 32;
                    source.connect(this.analyser);
                    // 尝试支持的mimeType格式
                                const supportedTypes = ['audio/webm', 'audio/mp4', 'audio/ogg', 'audio/wav'];
                                let mediaRecorderOptions = { audioBitsPerSecond: 16000 };
                                
                                // 找出浏览器支持的格式
                                for (const type of supportedTypes) {
                                    try {
                                        mediaRecorderOptions.mimeType = type;
                                        this.mediaRecorder = new MediaRecorder(this.stream, mediaRecorderOptions);
                                        console.log(`使用音频格式: ${type}`);
                                        break;
                                    } catch (e) {
                                        console.warn(`不支持 ${type}: ${e.message}`);
                                    }
                                }
                                
                                // 如果没有设置成功，使用默认格式
                                if (!this.mediaRecorder) {
                                    console.log('使用默认音频格式');
                                    this.mediaRecorder = new MediaRecorder(this.stream);
                                }
                                
                                // 重置状态
                                this.audioChunks = [];
                                
                                // 设置数据处理器
                                this.mediaRecorder.ondataavailable = (event) => {
                                    this.audioChunks.push(event.data);
                                };
                                
                                // 录音停止处理器
                                this.mediaRecorder.onstop = () => {
                                    this.onRecordingStop();
                                };
                                
                                // 开始录音
                                this.mediaRecorder.start(100); // 每100ms收集一次数据
                                
                                // 开始音量监测
                                this.startVolumeMeter();
                                
                                // 设置录音超时
                                this.recordingTimeout = setTimeout(() => {
                                    this.stop();
                                }, this.maxRecordingTime);
                                
                                // 更新UI
                                this.updateUIState('recording');
                                
                            } catch (error) {
                                console.error('录音初始化错误:', error);
                                this.handleError(error);
                            }
                        }
                   stop() {
                           if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
                               clearTimeout(this.recordingTimeout);
                               clearInterval(this.volumeInterval);
                               this.mediaRecorder.stop();
                           }
                       }
                   
                       onRecordingStop() {
                           // 停止所有音轨
                           if (this.stream) {
                               this.stream.getTracks().forEach(track => track.stop());
                           }
                           
                           // 处理录音数据
                           const mimeType = this.mediaRecorder.mimeType || 'audio/webm';
                           const audioBlob = new Blob(this.audioChunks, { type: mimeType });
                           this.processAudio(audioBlob);
                       }
                   
                       async processAudio(audioBlob) {
                           try {
                               const audioUrl = URL.createObjectURL(audioBlob);
                               const audioPlayer = document.getElementById(`${this.type}_audioPlayer`);
                               audioPlayer.src = audioUrl;
                               
                               // 存储处理后的音频
                               window[`${this.type}AudioBlob`] = audioBlob;
                               
                               // 更新UI
                               document.getElementById(`${this.type}_audioPreview`).classList.remove('d-none');
                               document.getElementById(`${this.type}_sendBtn`).disabled = false;
                               
                           } catch (error) {
                               console.error('音频处理错误:', error);
                               this.handleError(error);
                           }
                       }
                   
                       startVolumeMeter() {
                           if (!this.analyser) return;
                           
                           const bufferLength = this.analyser.frequencyBinCount;
                           const dataArray = new Uint8Array(bufferLength);
                           const volumeMeter = document.getElementById(`${this.type}_volumeMeter`);
                           
                           this.volumeInterval = setInterval(() => {
                               this.analyser.getByteFrequencyData(dataArray);
                               
                               let sum = 0;
                               for (let i = 0; i < bufferLength; i++) {
                                   sum += dataArray[i];
                               }
                               const average = sum / bufferLength;
                               
                               // 更新音量条
                               volumeMeter.style.width = `${average}%`;
                               
                               // 根据音量改变颜色
                               if (average > 70) {
                                   volumeMeter.style.backgroundColor = '#EF4444'; // 红色表示音量过高
                               } else if (average > 40) {
                                   volumeMeter.style.backgroundColor = '#3B82F6'; // 蓝色表示正常音量
                               } else {
                                   volumeMeter.style.backgroundColor = '#10B981'; // 绿色表示音量低
                               }
                           }, 100);
                       }
            

            updateUIState(state) {
                    const recordingStatus = document.getElementById(`${this.type}_recordingStatus`);
                    const startBtn = document.getElementById(`${this.type}_startBtn`);
                    const stopBtn = document.getElementById(`${this.type}_stopBtn`);
                    const sendBtn = document.getElementById(`${this.type}_sendBtn`);
                    const timer = document.getElementById(`${this.type}_timer`);
                    
                    switch (state) {
                        case 'recording':
                            recordingStatus.classList.remove('d-none');
                            startBtn.disabled = true;
                            stopBtn.disabled = false;
                            sendBtn.disabled = true;
                            
                            // 开始倒计时
                            let timeLeft = this.maxRecordingTime / 1000;
                            timer.textContent = `剩余时间: ${timeLeft}秒`;
                            
                            const countdown = setInterval(() => {
                                timeLeft--;
                                timer.textContent = `剩余时间: ${timeLeft}秒`;
                                
                                if (timeLeft <= 0) {
                                    clearInterval(countdown);
                                }
                            }, 1000);
                            
                            break;
                            
                        case 'stopped':
                            recordingStatus.classList.add('d-none');
                            startBtn.disabled = false;
                            stopBtn.disabled = true;
                            break;
                            
                        case 'ready':
                            sendBtn.disabled = false;
                            break;
                    }
                }
				handleError(error) {
				        showResult(`${this.type}_result`, 'error', `录音错误: ${error.message}`);
				        this.cleanup();
				        document.getElementById(`${this.type}_startBtn`).disabled = false;
				    }
				
				    cleanup() {
				        // 清理资源
				        if (this.stream) {
				            this.stream.getTracks().forEach(track => track.stop());
				        }
				        if (this.volumeInterval) {
				            clearInterval(this.volumeInterval);
				        }
				        if (this.recordingTimeout) {
				            clearTimeout(this.recordingTimeout);
				        }
				    }
				}

        // 创建录音器实例
        const voiceRecorder = new AudioRecorder('reg');
		
		
		// 录音按钮事件绑定
		document.getElementById('reg_startBtn').addEventListener('click', (e) => {
		    e.preventDefault();
		    voiceRecorder.start();
		});
		
		document.getElementById('reg_stopBtn').addEventListener('click', (e) => {
		    e.preventDefault();
		    voiceRecorder.stop();
		});
		
		document.getElementById('reg_sendBtn').addEventListener('click', (e) => {
		    e.preventDefault();
		    if (window.regAudioBlob) {
		        registerFeature();
		    } else {
		        showResult('reg_result', 'error', '请先录制音频');
		    }
		});
		
		// 显示结果信息（保持原有函数不变）
		function showResult(elementId, type, message) {
		    const resultElement = document.getElementById(elementId);
		    resultElement.textContent = message;
		    resultElement.className = 'result ' + type;
		    resultElement.classList.remove('d-none');
		    
		    setTimeout(() => {
		        resultElement.classList.add('d-none');
		    }, 5000);
		}
		
		
        // 滚动效果
        window.addEventListener('scroll', () => {
            if (window.scrollY > 10) {
                header.classList.add('py-2', 'shadow');
                header.classList.remove('py-4');
            } else {
                header.classList.add('py-4');
                header.classList.remove('py-2', 'shadow');
            }
        });

        // 移动端菜单
        mobileMenuButton.addEventListener('click', () => {
            mobileMenu.classList.toggle('hidden');
        });

        // 显示弹窗
        uploadBtn.addEventListener('click', () => {
            uploadModal.classList.remove('hidden');
            // 动画效果
            setTimeout(() => {
                modalContent.classList.remove('scale-95', 'opacity-0');
                modalContent.classList.add('scale-100', 'opacity-100');
            }, 10);
        });

        // 隐藏弹窗
        function hideModal() {
            modalContent.classList.remove('scale-100', 'opacity-100');
            modalContent.classList.add('scale-95', 'opacity-0');
            setTimeout(() => {
                uploadModal.classList.add('hidden');
                // 重置表单
                uploadForm.reset();
                photoPreview.classList.add('d-none');
                // 停止录音
                voiceRecorder.stop();
            }, 300);
        }

        closeModal.addEventListener('click', hideModal);
        cancelUpload.addEventListener('click', hideModal);

        // 点击弹窗外部关闭
        uploadModal.addEventListener('click', (e) => {
            if (e.target === uploadModal) {
                hideModal();
            }
        });

        // 照片预览
        photoInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                // 检查文件大小
                if (file.size > 5 * 1024 * 1024) {
                    alert('文件大小不能超过5MB');
                    return;
                }
                
                const reader = new FileReader();
                reader.onload = (event) => {
                    previewImage.src = event.target.result;
                    photoPreview.classList.remove('d-none');
                };
                reader.readAsDataURL(file);
            }
        });

        // 拖放上传
        photoUploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            photoUploadArea.classList.add('border-primary', 'bg-blue-50');
        });

        photoUploadArea.addEventListener('dragleave', () => {
            photoUploadArea.classList.remove('border-primary', 'bg-blue-50');
        });

        photoUploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            photoUploadArea.classList.remove('border-primary', 'bg-blue-50');

            if (e.dataTransfer.files.length) {
                const file = e.dataTransfer.files[0];
                // 检查文件类型
                if (!file.type.match('image.*')) {
                    alert('请上传图片文件');
                    return;
                }
                
                photoInput.files = e.dataTransfer.files;
                // 触发预览
                const event = new Event('change');
                photoInput.dispatchEvent(event);
            }
        });

        // 录音按钮事件
        document.getElementById('reg_startBtn').addEventListener('click', (e) => {
            e.preventDefault();
            voiceRecorder.start();
        });

        document.getElementById('reg_stopBtn').addEventListener('click', (e) => {
            e.preventDefault();
            voiceRecorder.stop();
        });

        document.getElementById('reg_sendBtn').addEventListener('click', (e) => {
            e.preventDefault();
            registerFeature();
        });

        // 注册声纹特征
        function registerFeature() {
            const name = nameInput.value.trim();
            const password = passwordInput.value.trim();
            const photoFile = photoInput.files[0];
            const audioBlob = window.regAudioBlob;
            
            if (!name || !password || !photoFile) {
                showResult('reg_result', 'error', '请填写姓名、密码并上传照片');
                return;
            }
            
            if (!audioBlob) {
                showResult('reg_result', 'error', '请先录制音频');
                return;
            }
            
            showResult('reg_result', 'warning', '正在注册声纹特征...');
            
            // 读取照片为Base64格式
            const reader = new FileReader();
            reader.onload = function(event) {
                const base64Image = event.target.result.split(',')[1]; // 去掉data:URL前缀
                
                // 创建FormData对象
                const formData = new FormData();
                formData.append('name', name);
                formData.append('password', password);
                formData.append('image', base64Image);
                formData.append('audio', audioBlob, 'voice.wav');
                
                // 发送到服务器
                fetch("http://127.0.0.1:5002/register", {
                    method: "POST",
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showResult('reg_result', 'success', data.message);
                        document.getElementById('reg_sendBtn').disabled = true;
                        
                        // 显示结果区域
                        resultArea.classList.remove('hidden');
                        
                        // 下载按钮点击事件
                        downloadBtn.addEventListener('click', () => {
                            const userData = {
                                "Name": name,
                                "Password": password,
                                "Image": base64Image,
                                "VoiceRegistered": true
                            };
                            const jsonData = JSON.stringify(userData, null, 2);
                            
                            const blob = new Blob([jsonData], { type: 'application/json' });
                            const url = URL.createObjectURL(blob);
                            const a = document.createElement('a');
                            a.href = url;
                            a.download = `${name}_profile.json`;
                            document.body.appendChild(a);
                            a.click();
                            document.body.removeChild(a);
                            URL.revokeObjectURL(url);
                        });
                    } else {
                        showResult('reg_result', 'error', data.message);
                        document.getElementById('reg_startBtn').disabled = false;
                    }
                })
                .catch(error => {
                    console.error('注册错误:', error);
                    showResult('reg_result', 'error', `注册失败: ${error.message}`);
                    document.getElementById('reg_startBtn').disabled = false;
                });
            };
            reader.readAsDataURL(photoFile);
        }

        // 显示结果信息
        function showResult(elementId, type, message) {
            const resultElement = document.getElementById(elementId);
            resultElement.textContent = message;
            
            // 移除所有状态类
            resultElement.classList.remove('success', 'error', 'warning', 'd-none');
            
            // 添加对应状态类
            resultElement.classList.add(type);
            
            // 显示结果
            resultElement.classList.remove('d-none');
            
            // 5秒后自动隐藏结果
            setTimeout(() => {
                resultElement.classList.add('d-none');
            }, 5000);
        }

        // 检查用户登录状态
        function checkLogin() {
            const username = sessionStorage.getItem('username');
            if (!username) {
                window.location.href = 'login.html';
            }
        }

        // 初始化
        checkLogin();
        
        // 主区域点击上传
        uploadArea.addEventListener('click', () => {
            uploadBtn.click();
        });
    </script>
</body>
</html>